package android.facebook.connect;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphObject;

public class FacebookActivity extends ListActivity{
 
	private ListAdapter adapter;	
	private HashMap<String, String> store = new HashMap<String, String>();	
	private ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
	private Session.StatusCallback statusCallback = new SessionStatusCallback();
	
	// Buttons
	Button btnFbLogin;
	Button btnFbGetStatuses;
	Button btnPostToWall;
	Button btnFbLogout;
	EditText postText;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
		btnFbLogout = (Button) findViewById(R.id.btn_fblogout);
		btnFbGetStatuses = (Button) findViewById(R.id.btn_get_statuses);
		btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
		postText = (EditText) findViewById(R.id.post_text);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
		
		//Checks if session is active and if so restores it
		Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }        
        }
        //Updates view
        updateView(); 
        for(int i=0;i<3;i++){frienders();}
        	
		/**
		 * Login button Click event
		 * */
		btnFbLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {			
				onClickLogin();
				
			}
		}); 
		
		/**
		 * Logout button Click event
		 * */
		btnFbLogout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {			
				onClickLogout();
			}
		}); 
		
		/**
		 * Getting info from facebook
		 * */
		btnFbGetStatuses.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//Reads all users friends name and id
				frienders();
				//Gets statuses from facebook
				
			}
		});

		/**
		 * Posting to Facebook Wall
		 * */
		btnPostToWall.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String status = postText.getText().toString();
				if (status.trim().length() > 0) {
					postToWall();
					//Sets postText to empty String after posting message on facebook wall
					postText.setText("");
				} else {
					//shows message if postText field is empty
					Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT).show();
				}			
			}
		});
			
	}
	
    @Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    private void updateView() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
        	//Updates View if user logs in
        	btnFbLogin.setVisibility(View.GONE);
			btnFbLogout.setVisibility(View.VISIBLE);
			btnFbGetStatuses.setVisibility(View.VISIBLE);
			btnPostToWall.setVisibility(View.VISIBLE);
			getListView().setVisibility(View.VISIBLE);
			postText.setVisibility(View.VISIBLE);
			btnFbLogout.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogout(); }
            });
        } else {
        	//Updates View if user logs out
        	btnFbLogout.setVisibility(View.GONE);
			btnFbLogin.setVisibility(View.VISIBLE);
			btnFbGetStatuses.setVisibility(View.GONE);
			btnPostToWall.setVisibility(View.GONE);
			getListView().setVisibility(View.GONE);
			postText.setVisibility(View.GONE);
			btnFbLogin.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogin(); }
            });
        }
    }

    private void onClickLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        } else {
            Session.openActiveSession(this, true, statusCallback);
        }
    }

    private void onClickLogout() {
        Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            updateView();
        }
    }

	/**
	 * Get information from facebook(statuses and time)
	 * */
	public void getStatuses() {	
		//FQL query for getting status messages and times from users friends
		String fqlQuery = "SELECT status_id, uid , message, time FROM status WHERE message != \"\" and (uid=me() or uid IN (SELECT uid2 FROM friend WHERE uid1 = me()))";
		Bundle params = new Bundle();
        params.putString("q", fqlQuery);
        Session session = Session.getActiveSession();
        
        params.putString("access_token", session.getAccessToken());
          	
		Request request = new Request(session,
	              "/fql",                         
	              params,                         
	              HttpMethod.GET,                 
	              new Request.Callback(){  
           
            public void onCompleted(Response response) {
                    GraphObject graphObject = response.getGraphObject();
                    
                    if (graphObject != null)
                    {
                        if (graphObject.getProperty("data") != null)
                        {
                            try {
                                String arry = graphObject.getProperty("data").toString();
                                JSONArray jsonNArray = new JSONArray(arry);

                                for (int i = 0; i < jsonNArray.length(); i++) {
                                    JSONObject jsonObject = jsonNArray.getJSONObject(i);
                                    //Get json objects from array
                                    String message = jsonObject.getString("message");
                                    long time = jsonObject.getLong("time");
                                    String uid = jsonObject.getString("uid");
                                    //converts unix timestamp to GMT     
                                    java.util.Date timeFromStatus = new java.util.Date((long)time*1000);
                                    String timeConverted = timeFromStatus.toGMTString();
                                         
                                    final HashMap<String, String> map = new HashMap<String, String>();
                                                                                                       
                                    map.put("name", store.get(uid));
                                    map.put("message", message);
                                    map.put("time", timeConverted);
                   				
                    				// adding HashList to ArrayList
                                    runOnUiThread(new Runnable() {
            							@Override
            							public void run() {
            								contactList.add(map);
            								((BaseAdapter) adapter).notifyDataSetChanged ();
            							}
            						});
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }                                       
                        }
                    }
            }                  
    }); 
       
		adapter = new SimpleAdapter(this, contactList,
			R.layout.list_item_facebook,
			new String[] { "message", "name", "time" }, new int[] {
					R.id.message, R.id.name, R.id.time });

		setListAdapter(adapter);
		Request.executeBatchAsync(request);
		ListView lv = getListView();
		lv.requestLayout();
		lv.setOnItemClickListener(null);
		contactList.clear();
	}
		
	/**
	 * Store user friend's names in HashMap
	 * */
	public HashMap<String, String> frienders() {
		//FQL query for getting friend names from user
		String fqlQuery = "SELECT name, uid FROM user  WHERE uid=me() or uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
		Bundle params = new Bundle();
        params.putString("q", fqlQuery);
        Session session = Session.getActiveSession();
        params.putString("access_token", session.getAccessToken());
          	
		Request request = new Request(session,
	              "/fql",                         
	              params,                         
	              HttpMethod.GET,                 
	              new Request.Callback(){  
           
            public void onCompleted(Response response) {
                    GraphObject graphObject = response.getGraphObject();
                    
                    if (graphObject != null)
                    {
                        if (graphObject.getProperty("data") != null)
                        {
                            try {
                                String arry = graphObject.getProperty("data").toString();
                                JSONArray jsonNArray = new JSONArray(arry);

                                for (int i = 0; i < jsonNArray.length(); i++) {
                                    JSONObject jsonObject = jsonNArray.getJSONObject(i);
                                    //Get json objects from array
                                    String uid = jsonObject.getString("uid");
                                    String name = jsonObject.getString("name");
                                         
                                    store.put(uid, name);
                                }
                            }catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }                                       
                        }
                    }
            }                  
    });
		Request.executeBatchAsync(request);
		getStatuses();
		return store;
	}
	
	/**
	 * post to facebook wall
	 * */
	public void postToWall() {
		// post on user's wall.
		Session session = Session.getActiveSession();

	        Bundle postParams = new Bundle();
	        
	        postParams.putString("message", postText.getText().toString());

	        Request.Callback callback= new Request.Callback() {
	            public void onCompleted(Response response) {
	                JSONObject graphResponse = response
	                                           .getGraphObject()
	                                           .getInnerJSONObject();
	                String postId = null;
	                try {
	                    postId = graphResponse.getString("id");
	                } catch (JSONException e) {
	                	// TODO Auto-generated catch block
	                }
	                FacebookRequestError error = response.getError();
	                if (error != null) {
	                  
	                    } else {
	                       
	                }
	            }
	        };

	        Request request = new Request(session, "me/feed", postParams, 
	                              HttpMethod.POST, callback);

	        RequestAsyncTask task = new RequestAsyncTask(request);
	        task.execute();
	        Toast.makeText(getApplicationContext(), "Message posted successfully", Toast.LENGTH_SHORT).show();
	}

}